// +----------------------------------------------------------------------
// | CmsWing [ 美业管理系统 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016 psi All rights reserved.
// +----------------------------------------------------------------------
// | Author: huang <2374266244@qq.com>
// +----------------------------------------------------------------------
'use strict';
import Base from './base.js';

export default class extends Base {
  /**
   * index action
   * @return {Promise} []
   */

  // 简单的取出子分类的函数
  async getChild(id) {
    // 取出子id
    let child_arr = [];
    const child = await this.model('or_subjecttype').where({pid: id}).getField('id');
    if (!think.isEmpty(child)) {
      for (var i = child.length - 1; i >= 0; i--) {
        child_arr.push(child[i]);
        child_arr = child_arr.concat(await this.getChild(child[i]));
      };
    };
    return child_arr;
  }

  // 制作inarray函数
  inArray(id, array) {
    if (!think.isEmpty(array)) {
      for (var i = 0; i < array.length; i++) {
        if (array[i] == id) {
          return true;
        };
      };
    };
    return false;
  }

  async subjectlistAction() {
    const page = this.post();
    const pages = page.pages;
    const limits = page.limits;
    const search = page.search;
    const zt = page.zt;
    const shopid = this.userinfo.departmentid;

    const data = await this.model('or_subject')
      .alias('s')
      .field('s.*,b.name as bname,c.name as cname')
      .join('`think_or_brand` b on b.id=s.brandid')
      .join('`think_or_subjectcategory` c on c.id=s.categoryid')
      .page(pages, limits)
      .order('s.id DESC')
      .where({'s.departmentid': shopid, 's.isdisable': zt, 's.name|s.remarks|b.name|c.name': ['like', '%' + search + '%']})
      .countSelect();

    return this.json(data);
  }

  async getcategoryAction() {
    const categoryid = JSON.parse(this.post('id'));
    let data = [];
    if (!think.isEmpty(categoryid)) {
      data = await this.model('or_subjectcategory').where({id: ['IN', categoryid]}).select();
    }
    return this.json(data);
  }

  // 新增、编辑项目
  async addeditAction() {
    const data = this.post();
    const orid = this.userinfo.departmentid;
    const addtime = Math.round(new Date().valueOf() / 1000);

    const repeat = await this.model('or_subject').where('departmentid=' + orid + ' AND (name="' + data.name + '" OR number="' + data.number + '") AND id!="' + data.id + '"').select();

    if (!think.isEmpty(repeat)) return this.fail('名称或编号重复');

    if (data.xstdtype == 1) {
      data.xspercent = Number(data.xspercent / 100).toFixed(2);
      data.xsfixed = 0;
    } else {
      data.xspercent = 0;
    }

    if (data.sgtdtype == 1) {
      data.sgpercent = Number(data.sgpercent / 100).toFixed(2);
      data.sgfixed = 0;
    } else {
      data.sgpercent = 0;
    }

    if (data.khtdtype == 1) {
      data.khpercent = Number(data.khpercent / 100).toFixed(2);
      data.khfixed = 0;
    } else {
      data.khpercent = 0;
    }

    // 编辑项目
    if (data.id * 1) {
      const upd = await this.model('or_subject').update(data);
      return upd ? this.success('编辑成功') : this.fail('编辑失败');
    }

    // 添加项目
    const add = {
      name: data.name,
      departmentid: orid,
      categoryid: data.categoryid,
      brandid: data.brandid,
      price: data.price,
      usetime: data.usetime,
      remarks: data.remarks,
      addtime: addtime,
      number: data.number,
      xstdtype: data.xstdtype,
      xspercent: data.xspercent,
      xsfixed: data.xsfixed,
      sgtdtype: data.sgtdtype,
      sgpercent: data.sgpercent,
      sgfixed: data.sgfixed,
      khtdtype: data.khtdtype,
      khpercent: data.khpercent,
      khfixed: data.khfixed
    };
    // 写入数据库
    const res = await this.model('or_subject').add(add);

    return res ? this.success('添加成功') : this.fail('添加失败');
  }

  // 选择项目
  async selectsubjectAction() {
    const cardid = this.get('cardid');
    const selectsub = await this.model('or_subject')
      .alias('s')
      .join('`think_or_subjectcategory` c on c.id = s.categoryid')
      .field('s.*,c.name as cname')
      .where({'s.departmentid': this.userinfo.departmentid, 's.isdisable': 0})
      .select();
    const validity = await this.model('or_card').where({id: cardid}).getField('validity');
    for (var i = 0, selectlen = selectsub.length; i < selectlen; i++) {
      selectsub[i]['validity'] = validity[0];
    }
    const relist = {
      'draw': '',
      'data': selectsub,
      'breadcrumb': ''
    	};
    return this.json(relist);
  }

  // 停用或启用项目
  async subjectstatusAction() {
    const id = this.post('id');
    const st = this.post('st');
    const shiyong = await this.ispull(id);
    if (!think.isEmpty(shiyong)) {
      return this.fail(shiyong.msg);
    }
    const res = await this.model('or_subject').where({id: id}).update({isdisable: st});
    if (st * 1) {
      return res ? this.success('停用成功') : this.fail('停用失败');
    } else {
      return res ? this.success('启用成功') : this.fail('启用失败');
    }
  }

  // 获取机构下的项目分类列表
  async subjectcategorylistAction() {
    const shopid = this.userinfo.departmentid;
    const clist = await this.model('or_subjectcategory').where({departmentid: shopid, pid: ['!=', 0], isdisable: 0}).select();
    const blist = await this.model('or_brand').where({departmentid: shopid}).select();
    const data = {
      cs: clist,
      bs: blist
    };
    return this.json(data);
  }

  async getsubjectcategorylistAction() {
    const shopid = this.userinfo.departmentid;
    const slist = await this.model('or_subjectcategory').where({departmentid: shopid, pid: ['!=', 0]}).select();
    const blist = await this.model('or_brand').where({departmentid: shopid}).select();
    const data = {
      cs: slist,
      bs: blist
    };
    return this.json(data);
  }

  // 如果当前项目被下属分店拉取，则机构不能操作当前项目
  async ispull(subjectid) {
    const isuse = await this.model('or_shop_subject').where({subjectid: subjectid}).select();
    if (!think.isEmpty(isuse)) return {msg: '当前项目以被分店拉取'};
    else return false;
  }

  // 保存项目的详细信息
  async saveSubjectInfoAction() {
    const data = this.post();
    data.banner = JSON.stringify(data.banner);
    const res = await this.model('or_subject').where({id: data.subjectid}).update(data);
    return res ? this.success('操作成功') : this.fail('操作失败');
  }

  // 获取项目的详细信息
  async getSubjectInfoAction() {
    const subjectid = this.get().id;
    const info = await this.model('or_subject').where({id: subjectid}).find();
    if (info.banner) {
      info.banner = JSON.parse(info.banner);
    }
    return this.json(info);
  }
}
